<?php
header('Content-Type: text/xml; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);

include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load("ns_core.m_public");

//自定义cp_id
define('DEFAULT_SOURCE_ID','jycm');

//$_POST['cmspost']='<ADI>
//<Metadata>
//<AMS Verb="delete" Asset_Class="packages" Asset_ID="JSBSDK00PAPT01810690" Asset_Name="女排世锦赛：非洲“姐妹”联手创历史" Provider_ID="JSBSDK" Provider="JSBSDK" Creation_Date="2018-11-07" Description="两支非洲球队喀麦隆和肯尼亚双双奏凯，完成了在世锦赛的历史性突破。" Version_Major="1" Version_Minor="0" Product="MOD"/>
//<App_Data Value="CableLabsVOD 1.1" Name="Metadata_Spec_Version" App="MOD"/>
//</Metadata>
//<Asset>
//<Metadata>
//<AMS Verb="" Asset_Class="title" Asset_ID="JSBSDK00PA0000181069" Asset_Name="女排世锦赛：非洲“姐妹”联手创历史" Provider_ID="JSBSDK" Provider="JSBSDK" Creation_Date="2018-11-07" Description="两支非洲球队喀麦隆和肯尼亚双双奏凯，完成了在世锦赛的历史性突破。" Version_Major="1" Version_Minor="0" Product="MOD"/>
//<App_Data Value="program" Name="Show_Type" App="MOD"/>
//<App_Data Value="0" Name="Issue_Number" App="MOD"/>
//<App_Data Value="JSBSDK00PA0000181069" Name="Original_Asset_ID" App="MOD"/>
//<App_Data Value="1" Name="Original_System_ID" App="MOD"/>
//<App_Data Value="1" Name="License_Type" App="MOD"/>
//<App_Data Value="Culture" Name="Genre" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Proper_Title" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Parallel_Proper_Title" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Subordinate_Title" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Alternative_ Title" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Title_Description" App="MOD"/>
//<App_Data Value="11" Name="Version_Description" App="MOD"/>
//<App_Data Value="" Name="Key_Words" App="MOD"/>
//<App_Data Value="两支非洲球队喀麦隆和肯尼亚双双奏凯，完成了在世锦赛的历史性突破。" Name="Description" App="MOD"/>
//<App_Data Value="" Name="Impressive_Dialogue" App="MOD"/>
//<App_Data Value="" Name="Impressive_Plot" App="MOD"/>
//<App_Data Value="" Name="Hot_Comments" App="MOD"/>
//<App_Data Value="" Name="Sentence_Review" App="MOD"/>
//<App_Data Value="" Name="Behind_Scenes" App="MOD"/>
//<App_Data Value="6.8" Name="IMDB_Rating" App="MOD"/>
//<App_Data Value="G" Name="MPAA_Rating" App="MOD"/>
//<App_Data Value="Y" Name="Season_Premiere" App="MOD"/>
//<App_Data Value="N" Name="Season_Finale" App="MOD"/>
//<App_Data Value="00:00:00" Name="Preview_Period" App="MOD"/>
//<App_Data Value="5" Name="Asset_Recommend_Class" App="MOD"/>
//<App_Data Value="0" Name="Chapter" App="MOD"/>
//<App_Data Value="2018" Name="Year" App="MOD"/>
//<App_Data Value="0.0" Name="Suggested_Price" App="MOD"/>
//<App_Data Value="Adult" Name="Audience" App="MOD"/>
//<App_Data Value="2056-01-01 20:00:00" Name="Subscriber_View_Limit" App="MOD"/>
//<App_Data Value="" Name="Region" App="MOD"/>
//</Metadata>
//<Asset>
//<Metadata>
//<AMS Verb="" Asset_Class="language" Asset_ID="JSBSDK00LAPT01810690" Asset_Name="女排世锦赛：非洲“姐妹”联手创历史" Provider_ID="JSBSDK" Provider="JSBSDK" Creation_Date="2018-11-07" Description="女排世锦赛：非洲“姐妹”联手创历史" Version_Major="1" Version_Minor="0" Product="MOD"/>
//<App_Data Value="zh" Name="Type" App="MOD"/>
//<App_Data Value="CH" Name="Description" App="MOD"/>
//<App_Data Value="zh_CN" Name="Tag" App="MOD"/>
//<App_Data Value="99" Name="Regin" App="MOD"/>
//<App_Data Value="南京一中" Name="Producers" App="MOD"/>
//<App_Data Value="" Name="Actors" App="MOD"/>
//<App_Data Value="" Name="Director" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Title" App="MOD"/>
//<App_Data Value="女排世锦赛：非洲“姐妹”联手创历史" Name="Title_Brief" App="MOD"/>
//</Metadata>
//</Asset>
//</Asset>
//</ADI>';

//http公共入口
class import extends \ns_model\message\message_queue
{
    /**
     *  参数
     * @var unknown
     */
    public $post_data = null;

    //simplexml解析后的數組
    private $arr_xml = null;

    //得到的simplexml对象
    private $sim_obj;

    //message_id
    private $message_id ;
    private $sp_id;
    /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info'=>array(
            'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
            'nns_message_id'=>'',  //上游消息ID
            'nns_cp_id'=>'', //上游CP标示
            'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json
            'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action'=>'', //操作 行为
            'nns_type'=>'', //消息 类型
            'nns_name'=>'',  //消息名称
            'nns_package_id'=>'',  //包ID（只对天威用 后期废用）
            'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
            'nns_encrypt'=>'', //广州电信悦ME 加密串
            'nns_content_number'=>'', //xml文件中包含的内容数量
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    /**
     * 初始化
     */
    public function __construct()
    {
        //加载 xml转为数组的np库
        \ns_core\m_load::load_np("np_xml_to_array.class.php");
        //初始化obj DC
        m_config::get_dc();
        //接收日志处理
        \m_config::write_message_receive_log("-----------消息接收开始-----------", DEFAULT_SOURCE_ID);
        $this->post_data  = $_POST;
        \m_config::write_message_receive_log("接收POST消息：". var_export($this->post_data, true), DEFAULT_SOURCE_ID);

        //判断是否为xml格式
        if( !m_public::is_xml($this->post_data['cmspost']) )
        {
            \m_config::write_message_receive_log("上游xml格式有误", DEFAULT_SOURCE_ID);
            return m_config::return_data(1,"上游xml格式有误");
        }

        //xml内容解析為數組
        $this->sim_obj = simplexml_load_string($this->post_data['cmspost']);
        $this->arr_xml = json_decode(json_encode($this->sim_obj),true);

        //sp_Id
        $this->sp_id =empty($this->post_data['sp_id'])?evn::get('project'):$this->post_data['sp_id'];

        //没有传入msgid，则随机一个
        $this->message_id = empty($this->post_data['msgid'])?np_guid_rand():$this->post_data['msgid'];
    }

    /**
     * 注入
     * @return string |string
     */
    public function import()
    {
        //元数据（post数据）用json存储
        $this->arr_in_message['base_info']['nns_message_xml'] = is_array($this->post_data) ? json_encode($this->post_data,JSON_UNESCAPED_UNICODE) : $this->post_data;

        $this->arr_in_message['base_info']['nns_message_time']=date('Ymdhis');
        //以asset_id作为message_id
        $this->arr_in_message['base_info']['nns_message_id']= $this->message_id;
        $this->arr_in_message['base_info']['nns_cp_id']=DEFAULT_SOURCE_ID;
        $this->arr_in_message['base_info']['nns_message_content']=$this->post_data['cmspost'];
        //获取行为nns_action       类型  nns_type  1 主媒资 | 2 分集   | 3片源
        $this->set_type_action();
        //消息队列入库方法
        $result = $this->push($this->arr_in_message);

        return $this->exec($result);
    }


    /**
     * @param $xml
     * 获取nns_type和nns_action
     */
    private function set_type_action()
    {
        //nns_type    1 主媒资  | 2 分集   |  3 片源       以Asset_Class的属性来判断
        $obj_asset_class = $this->sim_obj->xpath('//@Asset_Class');
        $arr_asset_class = array();
        //Asset_class  主媒资  title  分集 title  片源  movie
        foreach( $obj_asset_class as $asset_class )
        {
            $arr_asset_class[]=(string)$asset_class['Asset_Class'];
        }

        $arr_asset_class_count = array_count_values($arr_asset_class);

        if( in_array('movie',$arr_asset_class) )
        {
            //片源
            $this->arr_in_message['base_info']['nns_type'] = 3;
        }
        else
        {

            if( $arr_asset_class_count['title'] == 2 )
            {
                //分集
                $this->arr_in_message['base_info']['nns_type'] = 2;
            }
            else if( $arr_asset_class_count['title'] == 1)
            {
                //主媒资
                $this->arr_in_message['base_info']['nns_type'] = 1;
            }
            else
            {
                return;
            }
        }

        //nns_action 判定   1 增加 |  2修改  |  3 删除
        switch( $this->arr_in_message['base_info']['nns_type'] )
        {
            case 3:
                //片源
                $arr_re = $this->sim_obj->xpath('//AMS[contains(@Asset_Class,"movie")]')[0];
                $verb = (string)$arr_re['Verb'];
                $table = 'nns_vod_media';
                $import_name = 'nns_import_id';
                //片源注入id
                $import_value = (string)$arr_re['Asset_ID'];
                break;
            case 2:
                //分集
                $arr_re = $this->sim_obj->xpath('//AMS[contains(@Asset_Class,"title")]')[1];
                $verb = (string)$arr_re['Verb'];
                $table = 'nns_vod_index';
                $import_name = 'nns_import_id';
                //分集注入id
                $import_value = (string)$arr_re['Asset_ID'];
                break;
            case 1:
                //主媒资
                $arr_re = $this->sim_obj->xpath('//AMS[contains(@Asset_Class,"title")]')[0];
                $verb = (string)$arr_re['Verb'];
                $table = 'nns_vod';
                $import_name = 'nns_asset_import_id';
                //主媒资注入id
                $import_value = (string)$arr_re['Asset_ID'];
        }

        if( strtoupper($verb) == 'DELETE' )
        {
            $this->arr_in_message['base_info']['nns_action'] = 3;
        }
        else
        {
            //由sp，cp，注入id（这里以Asset_ID作为注入id），deleted四个参数判断媒资是否存在
            $sql = "select nns_id from {$table}
                            where {$import_name} = '{$import_value}'
                            and nns_cp_id = '".DEFAULT_SOURCE_ID."'
                            and nns_import_source = '".$this->sp_id."'
                            and nns_deleted = 0";

            $dc = nl_get_dc(array(
                'db_policy' => NL_DB_WRITE,
                'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
            ));

            $result = nl_db_get_one($sql, $dc->db());

            $this->arr_in_message['base_info']['nns_action'] = empty($result)?1:2;

        }
        return;
    }

    /**
     * @param $result
     * @return string
     */
    private function exec($result)
    {
        if($result['ret'] != 0)
        {
            \m_config::write_message_receive_log("注入结果失败：".var_export($result,true), DEFAULT_SOURCE_ID);
//            return "<result  ret=\"-1\"  reason=\"{$result['reason']}\"></result>";
            return 'fail';
        }
        else
        {
            \m_config::write_message_receive_log("注入结果成功", DEFAULT_SOURCE_ID);
//            return "<result  ret=\"{$result['ret']}\"  reason=\"success\"></result>";
            return 'ok';
        }
    }
    /**
     * 类销毁
     */
    public function __destruct()
    {
        \m_config::write_message_receive_log("-----------消息接收结束-----------", DEFAULT_SOURCE_ID);
    }
}
$http_import = new import();
$result_import = $http_import->import();

echo $result_import;